var salt = sessionStorage.getItem('usersalt');
/*统计*/

var title = '';
var firstdata = '';
var arr = [];

layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function() {
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : top.layer,
		$ = layui.jquery,
		laydate = layui.laydate,
		laytpl = layui.laytpl,
		table = layui.table;

	$("#saveImg").click(function() {
		html2canvas($('#perbin'), {
			onrendered: function(canvas) {

				var contentWidth = canvas.width;
				var contentHeight = canvas.height;

				//一页pdf显示html页面生成的canvas高度;
				var pageHeight = contentWidth / 595.28 * 841.89;
				//未生成pdf的html页面高度
				var leftHeight = contentHeight;
				//pdf页面偏移
				var position = 0;
				//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
				var imgWidth = 555.28;
				var imgHeight = 555.28 / contentWidth * contentHeight;

				var pageData = canvas.toDataURL('image/jpeg', 1.0);

				var pdf = new jsPDF('', 'pt', 'a4');
				//有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
				//当内容未超过pdf一页显示的范围，无需分页
				if(leftHeight < pageHeight) {
					pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight);
				} else {
					while(leftHeight > 0) {
						pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
						leftHeight -= pageHeight;
						position -= 841.89;
						//避免添加空白页
						if(leftHeight > 0) {
							pdf.addPage();
						}
					}
				}

				pdf.save('content.pdf');
			},
			//背景设为白色（默认为黑色）
			background: "#fff"
		})

	});
	/*时间选择器*/
	laydate.render({
		elem: '#statdate',
		trigger: 'click'

	});

	laydate.render({
		elem: '#enddate',
		trigger: 'click'

	});
	$.fn.zTree.init($("#danwe"), setting, zNodes);
	$('#resclas').click(function() {

		$('#userdutycompay').show();
		//		$('#resclas').val('')
		//		$('#userdutycompay').toggle();
	})
	$('#quedingqy').click(function() {
		$('#userdutycompay').hide();
	});

	var n = ''

	function zTreeOnCheck(event, treeId, treeNode) {
		//		nams = "";
		//		var checked = treeNode.checked;
		//				nams+= (treeNode?treeNode.name:"root") + ",";
		var treeObj = $.fn.zTree.getZTreeObj("userdutycompay");
		var nodes = treeObj.getCheckedNodes(true),
			n = "";
		for(var i = 0; i < nodes.length; i++) {
			n += nodes[i].name + ",";
			$('#resclas').val(n)

		}

	};

	var company;
	//*获取所有企业*/
	riskcompay();

	function riskcompay() {
		$.ajax({
			url: url + 'baseEnt/getAllEnt',
			dataType: 'json',
			async: false,
			type: "POST",
			data: {
				Token: salt
			},
			success: function(data) {

				$('#userdutycompay').empty();
				if(data.code == 0) {

					var list = data.data;
					company = list;

					//	      				var opt='<option value="0">请选择</option>'
					//	      				for(var i=0;i<list.length;i++){
					//	      					opt+='<option value="'+list[i].id+'" >'+list[i].name+'</option>'
					//	      				}
					//	      				
					//	      				$('#userdutycompay').append(opt);
					//	      				form.render();
				}

			},
			error: function(error) {
				console.log("获取失败");
			}
		});
	}

	var setting = {
		check: {
			enable: true
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onCheck: zTreeOnCheck
		}
	};
	var zNodes = company;
	/*---------------初始化树--------------*/
	$.fn.zTree.init($("#userdutycompay"), setting, zNodes);
	/*--------------获取选择的公司----------------*/
	function getval() {
		$('#container').hide();
		arr = []
		var treeObj = $.fn.zTree.getZTreeObj("userdutycompay");
		var nodes = treeObj.getCheckedNodes(true),
			v = "";
		for(var i = 0; i < nodes.length; i++) {
			v += nodes[i].name + ",";
			arr.push(nodes[i].id); //获取选中节点的值
		}
		return arr;
	}

	$('#getval').click(function() {

		findstatist();
	})
	/*----------------------筛选数据--------------------*/
	//findstatist();

	function findstatist() {
		var res = getval();

		//获取时间
		var stattime = $('#statdate').val();
		var endtime = $('#enddate').val();
		if(res.toString() == '') {
			layer.msg('请选择单位');
			return;
		}

		$.ajax({
			url: url + 'perilInfo/findStatistics',
			dataType: 'json',
			async: false,
			type: "POST",
			data: {
				Token: salt,
				entId: res.toString(),
				startTime: stattime,
				endTime: endtime

			},
			success: function(data) {
				if(data.code == 0) {
					$('#perbin').html("");
					var list = data.data;

					for(var i = 0; i < list.length; i++) {
						title = list[i].name;
						ent = title;
						if(title == '综合') {
							ent = "";
							for(var j = 1; j < list.length; j++) {
								ent += list[j].name + "、"
							}
						}
						var firstname = new Array();
						var leftinfo = '';
						var bottomifno = '';
						var tr = $('<tr></tr>');
						var filg = 0;
						var arr2 = new Array();
						var codeall = 0;
						var arr3 = [];
						for(var k = 0; k < list[i].data.length; k++) {
							codeall += list[i].data[k].Y;
							arr3.push(list[i].data[k].NAME);
							firstname.push({
								name: list[i].data[k].NAME,
								y: list[i].data[k].Y

							});
							arr2.push(list[i].data[k].Y);
							var htmldiv1 = ''

							leftinfo += '<div><p style="height:22px;">' + list[i].data[k].NAME + '</p></div>';

						}
						if(arr2.length > 0) {
							for(var h = 0; h < arr2.length; h++) {
								var code1 = (arr2[h] / codeall * 100).toFixed(2);
								htmldiv1 += '<div style="line-height:22px;"><span>' + arr3[h] + '</span><span style="margin-left:10px;">' + arr2[h] + '条</span><span style="margin-left:10px;">' + code1 + '%</span></div>';
							}
						} else {
							continue;
						}

						var divhtml = '<div><div style="float:left;font-weight:bold;">统计单位:</div><div style="float:left;margin-left:20px;">' + ent + '</div></div>';
						statdate = stattime;
						if(stattime == null || stattime == '') {
							statdate = "-"
						}
						enddate = endtime
						if(endtime == null || endtime == '') {
							enddate = "-"
						}
						var divhtml1 = '<div><div style="float:left;font-weight:bold;">统计时间:</div><div style="float:left;margin-left:20px;">' + statdate + "至" + enddate + '</div></div>';
						var divhtml2 = '<div><div style="float:left;font-weight:bold;">隐患详情:</div><div style="float:left;margin-left:20px;">' + htmldiv1 + '</div></div>';
						$('#perbin').append('<div style="overflow:hidden;margin:20px auto;"><div id="container' + i + 1 + '" style="float:left; height: 400px; width: 50%; margin: 0 auto"></div><div style="float:left; width: 50%;background:white;">' +
							'<p style="font-weight:bold;text-align:center;">隐患统计详情—' + title + '</p>' +
							divhtml + '<div style="clear:both;">' + divhtml1 + '<div style="clear:both;">' + divhtml2

							+
							'</div>' +
							'<div style="clear:both;">' +
							'<div></div>' +
							'</div>'

							+
							'</div>');
						Highcharts.chart('container' + i + 1, {
							chart: {
								plotBackgroundColor: null,
								plotBorderWidth: null,
								plotShadow: false,
								type: 'pie'
							},
							title: {
								text: '隐患统计—' + title
							},
							tooltip: {
								pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
							},
							plotOptions: {
								pie: {
									allowPointSelect: true,
									cursor: 'pointer',

									dataLabels: {
										enabled: false,
										format: '<b>{point.name}</b>: {point.percentage:.1f} %',
									},
									showInLegend: true
								}
							},
							series: [{
								name: 'Brands',
								colorByPoint: true,
								data: firstname
							}]
						});

					}
				}

			},
			error: function(error) {
				console.log("获取失败");
			}
		});

	}

});